package com.wyz.saas.common.notifice

import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import android.util.Log
import androidx.core.app.NotificationCompat
import java.util.*

abstract class AtomNotification {

    private val ctx: Context

    private val id: Int

    private var manager: NotificationManager? = null
        get() {
            if (field == null) {
                field = ctx.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            }
            return field
        }

    private val NOTIFY_CHANNEL_ID = "com.wyz.saas.common.notifice.AtomNotification"

    private val NOTIFY_CHANNEL_NAME = "com.wyz.saas.common.notifice.AtomNotification"

    constructor(ctx: Context) {
        this.ctx = ctx
        // Generate a random non-zero ID for the notification.
        val random = Random()
        var id: Int
        do id = random.nextInt() while (id == 0)
        this.id = id
    }

    fun getContext(): Context {
        return ctx
    }

    fun getID(): Int {
        return id
    }

    @Throws(Exception::class)
    protected abstract fun build(builder: NotificationCompat.Builder)

    fun push() {
        try {
            manager?.notify(id, create())
        } catch (e: Exception) {
            Log.e("AtomNotification", "Error while pushing notification ${e}") //NON-NLS
        }
    }

    @Throws(Exception::class)
    fun create(): Notification {
        val builder = NotificationCompat.Builder(ctx, NOTIFY_CHANNEL_ID)
        build(builder)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            try {
                val channel = NotificationChannel(
                    NOTIFY_CHANNEL_ID,
                    NOTIFY_CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_DEFAULT
                )
                manager?.createNotificationChannel(channel)
                builder.setChannelId(NOTIFY_CHANNEL_ID)
            } catch (e: Exception) {
            }
        }
        return builder.build()
    }
}